<template>
  <div>
    <el-input v-model="showDeptName" :placeholder="placeholder" @click="deptDialog">
      <template v-slot:append>
        <el-button icon="search" @click="deptDialog"></el-button>
      </template>
    </el-input>
    <el-dialog v-model="visibleDept" width="30%" :modal="false" :title="placeholder" :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form size="small" :inline="true">
        <el-form-item :label="$t('keyword')">
          <el-input v-model="filterText" :input-style="{ width: '150px' }"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="default">{{ $t("query") }}</el-button>
        </el-form-item>
      </el-form>
      <el-tree
        class="filter-tree"
        style="max-height: 50vh; overflow: scroll"
        :data="deptList"
        show-checkbox
        @check-change="handleCheckChange"
        :default-expanded-keys="expandedKeys"
        :props="{ label: 'name', children: 'children' }"
        :filter-node-method="filterNode"
        :highlight-current="true"
        node-key="id"
        ref="treeRef"
      ></el-tree>
      <template v-slot:footer>
        <el-button type="default" @click="cancelHandle()">{{ $t("cancel") }}</el-button>
        <el-button v-if="query" type="info" @click="clearHandle()">{{ $t("clear") }}</el-button>
        <el-button type="primary" @click="commitHandle()">{{ $t("confirm") }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {nextTick, ref, watch} from "vue";
import {IObject} from "@/types/interface";
import baseService from "@/service/baseService";
import {ElMessage} from "element-plus";
import {useI18n} from "vue-i18n";

const {t} = useI18n();

const filterText = ref("");
const visibleDept = ref(false);
const deptList = ref<any[]>([]);
const showDeptName = ref("");
const expandedKeys = ref<any[]>([]);
const treeRef = ref();

const props = defineProps({
  modelValue: Array,
  deptNames: String,
  query: Boolean,
  placeholder: String
});

watch(
  () => filterText.value,
  (val) => {
    treeRef.value.filter(val);
  }
);

watch(
  () => props.deptNames,
  (val) => {
    showDeptName.value = val as string;
  }
);

const deptDialog = () => {
  expandedKeys.value = [];
  visibleDept.value = true;
  getDeptList(props.modelValue);
};

const filterNode = (value: string, data: IObject) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};

const getDeptList = (val?: any[]) => {
  return baseService.get("/sys/dept/list").then((res) => {
    deptList.value = res.data;
    nextTick(() => {
      if (val && val.length > 0) {
        let arr = val.map((item: any) => item.deptId);
        let arr2: any[] = [];
        arr.forEach((item: any) => {
          arr2.push(item.split(",")[item.split(",").length - 1]);
        });
        treeRef.value.setCheckedKeys(arr2);
        expandedKeys.value = arr2;
      }
    });
  });
};

const cancelHandle = () => {
  visibleDept.value = false;
  deptList.value = [];
  filterText.value = "";
};

const emit = defineEmits(["update:modelValue", "update:deptNames"]);

const clearHandle = () => {
  emit("update:modelValue", []);
  emit("update:deptNames", "");
  showDeptName.value = "";
  visibleDept.value = false;
  deptList.value = [];
  filterText.value = "";
};

const handleCheckChange = (data: any, checked: any, indeterminate: any) => {
  console.log(data, checked, indeterminate);
};

const commitHandle = () => {
  const nodes = treeRef.value.getCheckedNodes();
  if (nodes.length === 0) {
    ElMessage.error(t("dept.chooseerror"));
    return;
  }
  let ids: any[] = [];
  nodes.forEach((item: any) => {
    if (item.bottom) {
      ids.push({
        deptId: item.id
      });
    }
  });
  let names = nodes.map((item: any) => {
    if (item.bottom) {
      return item.name
    }
  }).filter((item: any) => item).join(",");
  emit("update:modelValue", ids);
  emit("update:deptNames", names);
  showDeptName.value = names;
  visibleDept.value = false;
  deptList.value = [];
  filterText.value = "";
};
</script>
